from django.shortcuts import render, get_object_or_404, redirect
from sqlalchemy import create_engine
import redis
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.paginator import Paginator
from ai_inspect.models import *
from ai_inspect.forms import *
from django.http import Http404, HttpResponse
from django.db.models import Count, Sum
# Create your views here.

engine = create_engine("mysql+pymysql://root:Qiyuan*2023@43.137.4.113:3306/ai_inspect")


def main_index(request):
    return render(request, "index.html")


def station_index(request):
    stations = Station.objects.order_by('station_id')
    paginator = Paginator(stations, 10)
    page_number = request.GET.get('page', 1)
    try:
        current_page = paginator.page(page_number)
    except PageNotAnInteger:
        current_page = paginator.page(1)
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)
    context = {
        "paginator": paginator,
        "current_page": current_page
    }
    return render(request, "station/index.html", context)


def station_detail(request, station_id):
    station = get_object_or_404(Station, pk=station_id)
    try:
        aibox = get_object_or_404(AiBox, pk=station_id)
        channels = aibox.channel.order_by('channel_number').all()
        monitor_channel = Channel.objects.filter(aibox_sn=aibox.aibox_sn).filter(channel_number=aibox.monitor_channel).first()
        step_rules = station.step_rule.order_by('algorithm').all()
        period_rules = station.period_rule.order_by('algorithm').all()
    except Http404:
        aibox = None
        channels = None
        monitor_channel = None
        step_rules = None
        period_rules = None
    data_dict = {
        "station": station,
        "aibox": aibox,
        "channels": channels,
        "monitor_channel": monitor_channel,
        'step_rules': step_rules,
        'period_rules': period_rules
    }
    return render(request, "station/detail.html", data_dict)


def algorithm_index(request):
    algorithm_list = Algorithm.objects.all()
    context = {"algorithm_list": algorithm_list}
    return render(request, "algorithm/index.html", context)


def algorithm_create(request):
    if request.method == 'POST':
        form = AlgorithmForm(request.POST)
        # form['swap_maker'] = ','.join(form['swap_maker'])
        print(form)
        if form.is_valid():
            form.save()
            return redirect(f"/ai_inspect/algorithm/")
        else:
            print("上传的表单数据有误")
            print(request.POST)
    else:
        form = AlgorithmForm()
    return render(request, "algorithm/create.html", {'form': form})


def algorithm_metric(request, algorithm_name):
    algorithm = get_object_or_404(Algorithm, pk=algorithm_name)
    algorithm_metrics = get_object_or_404(AlgorithmMetric, pk=algorithm_name)
    data_dict = {
        "algorithm": algorithm,
        "algorithm_metrics": algorithm_metrics
    }
    return render(request, 'algorithm/metrics.html', data_dict)


def swap_record_list(request, station_id):
    station = get_object_or_404(Station, pk=station_id)
    swap_records = SwapRecord.objects.filter(stationNo=station_id).order_by('-stopTime')
    paginator = Paginator(swap_records, 10)
    page_number = request.GET.get('page', 1)
    try:
        current_page = paginator.page(page_number)
    except PageNotAnInteger:
        current_page = paginator.page(1)
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)
    context = {
        "station": station,
        "paginator": paginator,
        "current_page": current_page
    }
    return render(request, "station/swap_records.html", context)


def swap_record_photo(request, order_sn):
    swap_record = get_object_or_404(SwapRecord, pk=order_sn)
    station = get_object_or_404(Station, pk=swap_record.stationNo)
    swap_photos = SwapPhoto.objects.filter(order_sn=order_sn).order_by('-photo_time')
    context = {
        "station": station,
        "swap_record": swap_record,
        "swap_photos": swap_photos
    }
    return render(request, 'station/swap_record_photo.html', context)


def station_photo(request, station_id):
    station = get_object_or_404(Station, pk=station_id)
    station_photos = SwapPhoto.objects.filter(station_id=station_id).order_by('-photo_time').all()
    paginator = Paginator(station_photos, 9)
    page_number = request.GET.get('page', 1)
    try:
        current_page = paginator.page(page_number)
    except PageNotAnInteger:
        current_page = paginator.page(1)
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)
    context = {
        "station": station,
        "paginator": paginator,
        "current_page": current_page
    }
    return render(request, 'station/station_photo.html', context)


def station_date_photo(request, station_id, capture_date):
    station = get_object_or_404(Station, pk=station_id)
    sql = f"""
        SELECT * FROM ai_swap_station_photo
        WHERE station_id = '{station_id}'
            AND DATE(photo_time) = '{capture_date}'
    """
    station_photos = SwapPhoto.objects.raw(sql)
    return render(request, 'station/station_photo.html', {'station_photos': station_photos, 'station': station})


def station_channel_photo(request, station_id, channel_name, capture_date):
    station = get_object_or_404(Station, pk=station_id)
    sql = f"""
        SELECT * FROM ai_swap_station_photo
        WHERE station_id='{station_id}'
            AND channel_name='{channel_name}'
            AND DATE(photo_time)='{capture_date}'
    """
    station_photos = SwapPhoto.objects.raw(sql)
    return render(request, 'station/station_photo.html', {'station_photos': station_photos, 'station': station})


def aibox_index(request):
    aibox_list = Station.objects.select_related('aibox').all()
    paginator = Paginator(aibox_list, 10)
    page_number = request.GET.get('page', 1)
    try:
        current_page = paginator.page(page_number)
    except PageNotAnInteger:
        current_page = paginator.page(1)
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)
    context = {
        "paginator": paginator,
        "current_page": current_page
    }
    return render(request, 'aibox/index.html', context)


def inspect_request_index(request):
    request_list = InspectRequest.objects.filter(verification__isnull=True).order_by('-timestamp').all()[:10]
    return render(request, 'inspect_request/index.html', {'request_list': request_list})


def inspect_request_query(request, algorithm_topic, query):
    if query in ["no_target", "broken", "normal"]:
        request_list = InspectRequest.objects\
            .filter(inspect_name=algorithm_topic)\
            .filter(verification=query)\
            .order_by('-timestamp').all()[:20]
    elif query == "tp_intermediate":
        sql = f"""
            SELECT DISTINCT a.*
            FROM smart_maintenance.ai_inspect_request AS a
            LEFT JOIN smart_maintenance.ai_inspect_result AS b
            ON a.inspect_name=b.inspect_name
                AND a.photo_url=b.photo_url
            WHERE a.inspect_name = '{algorithm_topic}'
                AND a.verification IN ('normal', 'broken')
                AND b.result_type = 'intermediate_result'
        """
        request_list = InspectRequest.objects.raw(sql)[:20]
    elif query == "fp_intermediate":
        sql = f"""
            SELECT DISTINCT a.*
            FROM smart_maintenance.ai_inspect_request AS a
            LEFT JOIN smart_maintenance.ai_inspect_result AS b
            ON a.inspect_name=b.inspect_name
                AND a.photo_url=b.photo_url
            WHERE a.inspect_name = '{algorithm_topic}'
                AND a.verification='no_target'
                AND b.result_type = 'intermediate_result'
        """
        request_list = InspectRequest.objects.raw(sql)[:20]
    elif query == "tn_intermediate":
        sql = f"""
            SELECT DISTINCT a.*
            FROM smart_maintenance.ai_inspect_request AS a
            LEFT JOIN smart_maintenance.ai_inspect_result AS b
            ON a.inspect_name=b.inspect_name
                AND a.photo_url=b.photo_url
            WHERE a.inspect_name = '{algorithm_topic}'
                AND a.verification = 'no_target'
                AND b.result_type IS NULL
        """
        request_list = InspectRequest.objects.raw(sql)[:20]
    elif query == "fn_intermediate":
        sql = f"""
            SELECT DISTINCT a.*
            FROM smart_maintenance.ai_inspect_request AS a
            LEFT JOIN smart_maintenance.ai_inspect_result AS b
            ON a.inspect_name=b.inspect_name
                AND a.photo_url=b.photo_url
            WHERE a.inspect_name = '{algorithm_topic}'
                AND a.verification IN ('normal', 'broken')
                AND b.result_type IS NULL
        """
        request_list = InspectRequest.objects.raw(sql)[:20]
    elif query == "tp_final":
        sql = f"""
            SELECT DISTINCT a.*
            FROM smart_maintenance.ai_inspect_request AS a
            LEFT JOIN smart_maintenance.ai_inspect_result AS b
            ON a.inspect_name=b.inspect_name
                AND a.photo_url=b.photo_url
            WHERE a.inspect_name = '{algorithm_topic}'
                AND a.verification = 'broken'
                AND b.result_type = 'final_result'
        """
        request_list = InspectRequest.objects.raw(sql)[:20]
    elif query == "fp_final":
        sql = f"""
            SELECT DISTINCT a.*
            FROM smart_maintenance.ai_inspect_request AS a
            LEFT JOIN smart_maintenance.ai_inspect_result AS b
            ON a.inspect_name=b.inspect_name
                AND a.photo_url=b.photo_url
            WHERE a.inspect_name = '{algorithm_topic}'
                AND a.verification != 'broken'
                AND b.result_type = 'final_result'
        """
        request_list = InspectRequest.objects.raw(sql)[:20]
    elif query == "tn_final":
        sql = f"""
            SELECT DISTINCT a.*
            FROM smart_maintenance.ai_inspect_request AS a
            LEFT JOIN smart_maintenance.ai_inspect_result AS b
            ON a.inspect_name=b.inspect_name
                AND a.photo_url=b.photo_url
            WHERE a.inspect_name = '{algorithm_topic}'
                AND a.verification != 'broken'
                AND (b.result_type != 'final_result' or b.result_type IS NULL)
        """
        request_list = InspectRequest.objects.raw(sql)[:20]
    elif query == "fn_final":
        sql = f"""
            SELECT DISTINCT a.*
            FROM smart_maintenance.ai_inspect_request AS a
            LEFT JOIN smart_maintenance.ai_inspect_result AS b
            ON a.inspect_name=b.inspect_name
                AND a.photo_url=b.photo_url
            WHERE a.inspect_name = '{algorithm_topic}'
                AND a.verification = 'broken'
                AND (b.result_type != 'final_result' or b.result_type IS NULL)
        """
        request_list = InspectRequest.objects.raw(sql)[:20]
    elif query == "station_count":
        algorithm = Algorithm.objects.filter(algorithm_topic=algorithm_topic).first()
        request_stations = InspectRequest.objects.filter(inspect_name=algorithm_topic)\
            .values('station_id', 'station_name').distinct().values('station_id', 'station_name')
        result_stations = InspectResult.objects.filter(inspect_name=algorithm_topic)\
            .values('station_id', 'station_name').distinct().values('station_id', 'station_name')
        for request_station in request_stations:
            if request_station in result_stations:
                request_station['result_station'] = request_station['station_name']
        data_dict = {
            "stations": request_stations,
            "algorithm": algorithm
        }
        return render(request, 'station/algorithm_count.html', data_dict)
    else:
        return redirect("/ai_inspect/algorithm")
    return render(request, 'inspect_request/index.html', {'request_list': request_list})


def algorithm_request(request, algorithm_topic):
    algorithm_requests = InspectRequest.objects\
        .filter(inspect_name=algorithm_topic)\
        .filter(verification__isnull=True)\
        .order_by('-timestamp').all()
    paginator = Paginator(algorithm_requests, 10)
    page_number = request.GET.get('page', 1)
    try:
        current_page = paginator.page(page_number)
    except PageNotAnInteger:
        current_page = paginator.page(1)
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)
    context = {
        "paginator": paginator,
        "current_page": current_page
    }
    return render(request, 'inspect_request/index.html', context)


def station_algorithm_request(request, algorithm_topic, station_id):
    algorithm_requests = InspectRequest.objects\
        .filter(inspect_name=algorithm_topic)\
        .filter(verification__isnull=True)\
        .filter(station_id=station_id)\
        .order_by('-timestamp').all()
    paginator = Paginator(algorithm_requests, 10)
    page_number = request.GET.get('page', 1)
    try:
        current_page = paginator.page(page_number)
    except PageNotAnInteger:
        current_page = paginator.page(1)
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)
    context = {
        "paginator": paginator,
        "current_page": current_page
    }
    return render(request, 'inspect_request/index.html', context)


def inspect_request_detail(request, request_name):
    try:
        inspect_request = get_object_or_404(InspectRequest, pk=request_name)
        intermediate_results = InspectResult.objects\
            .filter(request_name=request_name)\
            .filter(result_type="intermediate_result").all()
        final_results = InspectResult.objects\
            .filter(request_name=request_name) \
            .filter(result_type="final_result").all()
        data_dict = {
            'inspect_request': inspect_request,
            'intermediate_results': intermediate_results,
            'final_results': final_results
        }
        return render(request, 'inspect_request/detail.html', data_dict)
    except Http404:
        close_script = """
                        <!DOCTYPE html>
                        <html>
                        <head>
                            <meta charset="UTF-8">
                            <title>未查询到巡检请求</title>
                        </head>
                        <body>
                            <script type="text/javascript">
                                // 提示用户（可选）
                                alert('数据提交成功，窗口将自动关闭...');
                                // 关闭当前窗口
                                window.close();
                            </script>
                        </body>
                        </html>
                        """
        return HttpResponse(close_script)


def inspect_request_verify(request, request_name, verification):
    inspect_request = get_object_or_404(InspectRequest, pk=request_name)
    inspect_request.verification = verification
    inspect_request.save()
    # next_request = InspectRequest.objects.filter(inspect_name=inspect_request.inspect_name)\
    #     .filter(verification__isnull=True)\
    #     .order_by('-timestamp').first()
    # if next_request:
    #     return redirect(f"/inspect_request/{next_request.request_name}/")
    # else:
    #     return redirect(f"/algorithm_request/{inspect_request.inspect_name}/")
    close_script = """
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <title>提交成功</title>
                </head>
                <body>
                    <script type="text/javascript">
                        // 提示用户（可选）
                        alert('数据提交成功，窗口将自动关闭...');
                        // 关闭当前窗口
                        window.close();
                    </script>
                </body>
                </html>
                """
    return HttpResponse(close_script)


def inspect_result_index(request):
    result_list = InspectResult.objects.filter(result_type="final_result").order_by('-timestamp').all()[:20]
    return render(request, 'inspect_result/index.html', {'result_list': result_list})


def algorithm_result(request, algorithm_topic):
    result_list = InspectResult.objects\
        .filter(result_type="final_result")\
        .filter(inspect_name=algorithm_topic)\
        .filter(verification__isnull=True)\
        .order_by('-timestamp').all()[:10]
    return render(request, 'inspect_result/index.html', {'result_list': result_list})


def inspect_result_detail(request, result_id):
    inspect_result = get_object_or_404(InspectResult, pk=result_id)
    data_dict = {
        'inspect_result': inspect_result,
    }
    return render(request, 'inspect_result/detail.html', data_dict)


def inspect_result_verify(request, result_id, verification):
    result = get_object_or_404(InspectResult, pk=result_id)
    result.verification = verification
    result.save()
    next_result = InspectResult.objects.filter(inspect_name=result.inspect_name).filter(result_type="final_result").filter(verification__isnull=True).order_by('-timestamp').first()
    if next_result:
        return redirect(f"/ai_inspect/inspect_result/{next_result.result_id}/")
    else:
        return redirect(f"/ai_inspect/algorithm_result/{result.inspect_name}/")


def step_rule_create(request, station_id):
    if request.method == 'GET':
        station = get_object_or_404(Station, pk=station_id)
        aibox = get_object_or_404(AiBox, pk=station_id)
        algorithms = Algorithm.objects.filter(inspect_type='基于换电步骤').filter(swap_maker__icontains=station.station_maker)
        channels = aibox.channel.all()
        steps = RobotStep.objects.filter(robot_type=station.robot_type)
        data_dict = {
            "station": station,
            "algorithms": algorithms,
            "channels": channels,
            "steps": steps,
        }
        return render(request, "rule/step_rule_create.html", data_dict)
    if request.method == 'POST':
        form = StepRuleForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, "基于换电步骤的巡检规则添加成功！")
            return redirect(f"/ai_inspect/station/{request.POST['station']}/")
        else:
            return redirect(f"/ai_inspect/step_rule_create/{request.POST['station']}/")


def period_rule_create(request, station_id):
    if request.method == 'GET':
        station = get_object_or_404(Station, pk=station_id)
        aibox = get_object_or_404(AiBox, pk=station_id)
        algorithms = Algorithm.objects.filter(inspect_type='周期性').filter(swap_maker__icontains=station.station_maker)
        channels = aibox.channel.all()
        data_dict = {
            "station": station,
            "algorithms": algorithms,
            "channels": channels,
        }
        return render(request, "rule/period_rule_create.html", data_dict)
    if request.method == 'POST':
        form = PeriodRuleForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, "周期性巡检规则添加成功！")
            return redirect(f"/ai_inspect/station/{request.POST['station']}/")
        else:
            return redirect(f"/ai_inspect/period_rule_create/{request.POST['station']}/")


def period_rule_delete(request, station_id, rule_id):
    if request.method == 'GET':
        period_rule = get_object_or_404(PeriodRule, pk=rule_id)
        period_rule.delete()
        return redirect(f"/ai_inspect/station/{station_id}")
    else:
        return redirect("/ai_inspect/")


def step_rule_delete(request, station_id, rule_id):
    if request.method == 'GET':
        step_rule = get_object_or_404(StepRule, pk=rule_id)
        step_rule.delete()
        return redirect(f"/ai_inspect/station/{station_id}")
    else:
        return redirect("/ai_inspect/")


def channel_create(request, station_id):
    if request.method == 'GET':
        station = get_object_or_404(Station, pk=station_id)
        data_dict = {
            "station": station,
        }
        return render(request, "channel/create.html", data_dict)
    if request.method == 'POST':
        form = ChannelForm(request.POST)
        if form.is_valid():
            # 实时更新redis
            channel_number = request.POST['channel_number']
            channel_name = request.POST['channel_name']
            channel_ip = request.POST['channel_ip']
            channel_url = request.POST['channel_url']
            redis_channel = redis.Redis(host='43.137.4.113', port=6379,
                                        password='qiyuan2023', db=6, decode_responses=True)
            redis_channel.hset(f"{station_id}:{channel_number}", 'channel_name', channel_name)
            redis_channel.hset(f"{station_id}:{channel_number}", 'channel_ip', channel_ip)
            redis_channel.hset(f"{station_id}:{channel_number}", 'channel_url', channel_url)
            redis_channel.close()
            form.save()
            messages.success(request, "监控通道添加成功！")
            return redirect(f"/ai_inspect/station/{request.POST['station']}/")
        else:
            return redirect(f"/ai_inspect/channel_create/{request.POST['station']}/")


def channel_update(request, station_id, channel_id):
    if request.method == 'GET':
        station = get_object_or_404(Station, pk=station_id)
        channel = get_object_or_404(Channel, pk=channel_id)
        data_dict = {
            "station": station,
            "channel": channel,
        }
        return render(request, "channel/update.html", data_dict)
    if request.method == 'POST':
        channel = get_object_or_404(Channel, pk=channel_id)
        form = ChannelForm(request.POST, instance=channel)
        if form.is_valid():
            # 实时更新redis
            channel_number = request.POST['channel_number']
            channel_name = request.POST['channel_name']
            channel_ip = request.POST['channel_ip']
            channel_url = request.POST['channel_url']
            redis_channel = redis.Redis(host='43.137.4.113', port=6379,
                                        password='qiyuan2023', db=6, decode_responses=True)
            redis_channel.hset(f"{station_id}:{channel_number}", 'channel_name', channel_name)
            redis_channel.hset(f"{station_id}:{channel_number}", 'channel_ip', channel_ip)
            redis_channel.hset(f"{station_id}:{channel_number}", 'channel_url', channel_url)
            form.save()
            messages.success(request, "监控通道更新成功！")
            return redirect(f"/ai_inspect/station/{station_id}/")
        else:
            messages.success(request, "监控通道更新失败！")
            return redirect(f"/ai_inspect/channel_update/{station_id}/{channel_id}/")


def channel_delete(request, station_id, channel_id):
    if request.method == 'GET':
        channel = get_object_or_404(Channel, pk=channel_id)
        channel.delete()
        return redirect(f"/ai_inspect/station/{station_id}")
    else:
        return redirect("/ai_inspect/")


def aibox_create(request, station_id):
    station = get_object_or_404(Station, pk=station_id)
    if request.method == 'POST':
        form = AiboxCreateForm(request.POST)
        if form.is_valid():
            form.save()
            # 同步redis数据库
            redis_aibox = redis.Redis(host='43.137.4.113', port=6379,
                                      password='qiyuan2023', db=3, decode_responses=True)
            redis_aibox.hset(request.POST['aibox_sn'], 'station_id', station_id)
            redis_station = redis.Redis(host='43.137.4.113', port=6379,
                                        password='qiyuan2023', db=4, decode_responses=True)
            redis_station.hset(station_id, 'device_sn', request.POST['aibox_sn'])
            redis_station.hset(station_id, 'url', request.POST['aibox_url'])
            redis_station.hset(station_id, 'business_unit', station.business_unit)
            redis_station.hset(station_id, 'group_id', station.group_id)
            redis_station.hset(station_id, 'station_id', station_id)
            redis_station.hset(station_id, 'station_name', station.station_name)
            redis_station.close()
            redis_aibox.close()
            return redirect(f"/ai_inspect/station/{station_id}/")
        else:
            print("上传的表单数据有误")
            print(request.POST)
    else:
        form = AiboxCreateForm()
    return render(request, "aibox/create.html", {'form': form, 'station': station})


def aibox_update(request, station_id):
    station = get_object_or_404(Station, pk=station_id)
    aibox = get_object_or_404(AiBox, pk=station_id)
    channels = aibox.channel.all()
    monitor_channel = Channel.objects.filter(aibox_sn=aibox.aibox_sn).filter(
        channel_number=aibox.monitor_channel).first()
    if request.method == 'POST':
        form = AiboxUpdateForm(request.POST, instance=aibox)
        if form.is_valid():
            form.save()
            # 更新redis
            redis_station = redis.Redis(host='43.137.4.113', port=6379,
                                        password='qiyuan2023', db=4, decode_responses=True)
            redis_station.hset(station_id, 'url', request.POST['aibox_url'])
            redis_station.hset(station_id, 'station_name', station.station_name)
            redis_station.hset(station_id, 'business_unit', station.business_unit)
            redis_station.hset(station_id, 'group_id', station.group_id)
            redis_station.hset(station_id, 'station_id', station_id)
            redis_station.hset(station_id, 'monitor_channel', request.POST['monitor_channel'])
            redis_station.close()
            return redirect(f"/ai_inspect/station/{request.POST['station_id']}/")
        else:
            print(request.POST)
    else:
        form = AiboxUpdateForm(instance=aibox)
    return render(request, 'aibox/update.html', {
        'form': form,
        'aibox': aibox,
        'station': station,
        'channels': channels,
        'monitor_channel': monitor_channel,
    })


def station_create(request):
    if request.method == 'POST':
        form = StationForm(request.POST)
        if form.is_valid():
            form.save()
            # 同步redis数据库
            redis_station = redis.Redis(host='43.137.4.113', port=6379,
                                        password='qiyuan2023', db=4, decode_responses=True)
            redis_station.hset(request.POST['station_id'], 'station_id', request.POST['station_id'])
            redis_station.hset(request.POST['station_id'], 'station_name', request.POST['station_name'])
            redis_station.hset(request.POST['station_id'], 'business_unit', request.POST['business_unit'])
            redis_station.close()
            return redirect(f"/ai_inspect/station/{request.POST['station_id']}/")
        else:
            print("上传的表单数据有误")
            print(request.POST)
    else:
        form = StationForm()
    return render(request, "station/create.html", {'form': form})


def station_update(request, station_id):
    station = get_object_or_404(Station, pk=station_id)
    if request.method == 'POST':
        form = StationForm(request.POST, instance=station)
        if form.is_valid():
            form.save()
            return redirect(f"/ai_inspect/station/{request.POST['station_id']}/")
        else:
            print("上传的表单数据有误")
            print(request.POST)
    else:
        form = StationForm(instance=station)
    return render(request, "station/update.html", {'form': form, 'station': station})


def step_rule_update(request, station_id, rule_id):
    if request.method == 'GET':
        rule = get_object_or_404(StepRule, pk=rule_id)
        station = get_object_or_404(Station, pk=station_id)
        aibox = get_object_or_404(AiBox, pk=station_id)
        algorithms = Algorithm.objects.filter(inspect_type='基于换电步骤').filter(swap_maker__icontains=station.station_maker)
        channels = aibox.channel.all()
        steps = RobotStep.objects.filter(robot_type=station.robot_type)
        data_dict = {
            "station": station,
            "rule": rule,
            "algorithms": algorithms,
            "channels": channels,
            "steps": steps,
        }
        return render(request, "rule/step_rule_update.html", data_dict)
    if request.method == 'POST':
        rule = get_object_or_404(StepRule, pk=rule_id)
        form = StepRuleForm(request.POST, instance=rule)
        if form.is_valid():
            form.save()
            messages.success(request, "巡检规则更新成功！")
            return redirect(f"/ai_inspect/station/{station_id}/")
        else:
            messages.success(request, "巡检规则更新失败！")
            return redirect(f"/ai_inspect/step_rule_update/{station_id}/{rule_id}/")


def period_rule_update(request, station_id, rule_id):
    if request.method == 'GET':
        station = get_object_or_404(Station, pk=station_id)
        aibox = get_object_or_404(AiBox, pk=station_id)
        channels = aibox.channel.all()
        algorithms = Algorithm.objects.filter(inspect_type='周期性').filter(swap_maker__icontains=station.station_maker)
        rule = get_object_or_404(PeriodRule, pk=rule_id)
        data_dict = {
            "station": station,
            "rule": rule,
            "channels": channels,
            "algorithms": algorithms,
        }
        return render(request, "rule/period_rule_update.html", data_dict)
    if request.method == 'POST':
        rule = get_object_or_404(PeriodRule, pk=rule_id)
        form = PeriodRuleForm(request.POST, instance=rule)
        if form.is_valid():
            form.save()
            messages.success(request, "巡检规则更新成功！")
            return redirect(f"/ai_inspect/station/{station_id}/")
        else:
            messages.success(request, "巡检规则更新失败！")
            return redirect(f"/ai_inspect/period_rule_update/{station_id}/{rule_id}/")


def station_battery_count_index(request):
    results = StationBattery.objects.values("business_unit")\
        .annotate(station_count=Count('station_id'))\
        .annotate(battery_count=Sum('battery_count'))\
        .annotate(battery_count_validate=Sum('battery_count_validate'))\
        .order_by('business_unit')
    return render(request, "station/battery_count_index.html", {"results": results})


def station_battery_count_list(request, business_unit):
    stations = StationBattery.objects.filter(business_unit=business_unit).order_by('station_name').all()
    return render(request, "station/battery_count_list.html", {"stations": stations, "business_unit": business_unit})


def station_battery_count_validate(request, station_id):
    if request.method == 'GET':
        station = get_object_or_404(StationBattery, pk=station_id)
        return render(request, "station/battery_count_validate.html", {"station": station})
    if request.method == 'POST':
        station_battery = get_object_or_404(StationBattery, pk=station_id)
        form = StationBatteryForm(request.POST, instance=station_battery)
        if form.is_valid():
            form.save()
            messages.success(request, "仓内电池数量更新成功！")
            return redirect(f"/ai_inspect/station_battery_count_list/{station_battery.business_unit}/")
        else:
            messages.success(request, "仓内电池数量更新失败！")
            return redirect(f"/ai_inspect/station_battery_count_validate/{station_id}/")